<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>LayIM社交模式 在线演示 - Layui</title>
    <link rel="stylesheet" href="/Public/Swoole/layui/build/css/layui.css" media="all">
    <link rel="stylesheet" href="/Public/Swoole/css/global.css" media="all">
    <link rel="stylesheet" href="/Public/Swoole/css/demo.css?t=20160620" media="all">
</head>

<body>
    <div class="header">
        <div class="layui-main">
            <a class="logo" href="http://www.layui.com">
                <!-- <img src="./images/logo.png" alt="layui"> -->
            </a>
            <span class="meau">
      <a href="/">首页</a>
      <a href="{:U('Swoole/logout')}">退出</a>
    </span>
        </div>
    </div>
    <div class="layui-main" style="margin-top: 60px;">
        <div class="demo-footer" style="margin-top: 100px; line-height: 30px;">
            <p>你现在阅览的是：LayIM社交模式，一般会用到里面的全部功能</p>
            <p>
                此作品由Layui的贤心出品， 在此做下swoole当服务器的范例
            </p>
            <p class="demo-content" style="margin-top: 30px;">
                <a href="http://www.layui.com/doc/layim.html">文档</a>
                <a href="http://layim.layui.com/">关于Layim</a></p>
            <p>假如没人陪你聊天， 自己双开， 自己聊吧</p>
                <p class="demo-content"><a href="http://swoole.com/">关于Swoole</a></p>
            <p class="demo-content">(因为太忙，暂时关闭， 可查看swoole版聊天室的演示, <a href="{:U('Swoole/chat')}">聊天室</a>)</p>
        </div>
    </div>
    <script src="/Public/Swoole/layui/build/layui.js"></script>
    <script>
    var socket, name, client_id, client_list = {};
    var name = '{$username}';
    var userid = {$userid};
    layui.use(['layim', 'socket', 'layer'], function(layim) {
        var layer = layui.layer;

        connect();
        // 连接服务端
        function connect() {
            socket = new WebSocket('ws://pdosgk.com:9505');
            //连接成功时触发
            socket.onopen = onopen;
            //监听收到的消息
            socket.onmessage = onmessage;
            socket.onclose = function() {
                layer.msg('和服务器连接失败', {
                    shift: 6,
                    offset: 0,
                    time: 9000
                });
                console.log("连接关闭，定时重连");
                //connect();
            };
            socket.onerror = function() {
                layer.msg('和服务器连接失败', {
                    shift: 6,
                    offset: 0,
                    time: 9000
                });
                console.log("出现错误");
            };
        }

        function onopen() {
            // 登录
            var login_data = '{"type":"login","username":"' + name.replace(/"/g, '\"') + '","userid":' + userid + '}';
            console.log("websocket握手成功，发送登录数据:" + login_data);
            socket.send(login_data);
            layer.msg('服务器连接成功', {
                shift: 6,
                offset: 0,
                time: 1000
            });
            console.log('XXX连接成功');
            //如果列表不为空
            for (var p in client_list) {
                layim.removeList({
                    type: 'friend', //或者group
                    id: p //好友或者群组ID
                });
            }
            initim();
        };
        // 服务端发来消息时
        function onmessage(e) {
            console.log(e.data);
            var data = eval("(" + e.data + ")");
            switch (data['type']) {
                // 服务端ping客户端
                case 'ping':
                    ws.send('{"type":"pong"}');
                    break;;
                    // 登录 更新用户列表
                case 'login':
                    if (data['client_list']) {
                        client_list = data['client_list'];
                        friend_list();
                    } else {
                        client_list[data['userid']] = {
                            'userid': data['userid'],
                            'username': data['username']
                        };
                        friend_list_new(data['userid'], data['username']);
                    }
                    console.log(data['username'] + "登录成功");
                    break;
                    // 发言
                case 'chatMessage':
                    layim.getMessage({
                        username: data.from_client_name,
                        avatar: data.avatar,
                        id: data.from_client_id,
                        type: "friend",
                        content: data.content,
                        time: data.time
                    });
                    break;
                    // 用户退出 更新用户列表
                case 'not_online':
                    layer.msg('对方不在线， 消息对方上线时可见', {
                        shift: 6,
                        offset: 0,
                        time: 9000
                    });
                    break;
                case 'logout':
                    layim.removeList({
                        type: 'friend', //或者group
                        id: data['userid'] //好友或者群组ID
                    });
                    delete client_list[data['userid']];
            }
        }

        function friend_list() {
            //获取列表
            for (var p in client_list) {
                if (userid != client_list[p]['userid']) {
                    layim.addList({
                        type: 'friend',
                        avatar: "http://tp2.sinaimg.cn/2386568184/180/40050524279/0",
                        username: client_list[p]['username'],
                        groupid: 2,
                        id: client_list[p]['userid'],
                        remark: ""
                    });
                }

            }

        }

        function friend_list_new(user_id, name) {
            //如果重复登陆， 当前用户下线
            if (user_id == userid) {
                alert("在别处登陆l");
                socket.close();
                window.close();
            }
            layer.msg("【" + name + '】上线了，打开在线好友列表和TA聊聊吧', {
                shift: 6,
                offset: 0,
                time: 9000
            });

            //新成员
            layim.addList({
                type: 'friend',
                avatar: "http://tp2.sinaimg.cn/2386568184/180/40050524279/0",
                username: name,
                groupid: 2,
                id: user_id,
                remark: ""
            });
        }

        function say() {

        }

        function initim() {
            //基础配置
            layim.config({

                //初始化接口
                init: {
                    url: '{:U('Swoole/ajax_getList')}',
                    data: {}
                }

                //简约模式（不显示主面板）
                //,brief: true

                //查看群员接口
                ,
                members: {
                    url: './json/getMembers.json',
                    data: {}
                }

                ,
                uploadImage: {
                    url: '' //（返回的数据格式见下文）
                        ,
                    type: '' //默认post
                }

                ,
                uploadFile: {
                    url: '' //（返回的数据格式见下文）
                        ,
                    type: '' //默认post
                }

                //,skin: ['http://cdn.firstlinkapp.com/upload/2016_4/1461747766565_14690.jpg'] //皮肤
                //,isgroup: false //是否开启群组
                ,
                chatLog: './demo/chatlog.html?id=' //聊天记录地址
                    ,
                find: '/index.php/Home/Swoole/layimFind.html'
                    //,copyright: true //是否授权
            });
            //监听发送消息
            layim.on('sendMessage', function(data) {
                var To = data.to;
                var message_data = '{"type":"chatMessage","to_client_id":' + To.id + ',"username":"' + data.mine.username + '", "avatar":"' + data.mine.avatar + '", "content":"' + data.mine.content.replace(/"/g, '\"') + '"}';
                //发送消息倒Socket服务

                console.log(message_data);
                socket.send(message_data);

            });

            //监听在线状态的切换事件
            layim.on('online', function(data) {
                console.log(data);
            });



            //监听收到的聊天消息

            layim.on('chatMessage', function(res) {
                layim.getMessage({
                    username: res.name,
                    avatar: res.avatar,
                    id: res.id,
                    type: res.type,
                    content: res.content
                });
            });


            //layim建立就绪
            layim.on('ready', function(res) {

            });

            //监听查看群员
            layim.on('members', function(data) {
                console.log(data);
            });

            //监听聊天窗口的切换
            layim.on('chatChange', function(data) {
                console.log(data);
            });
        }

    });
    </script>
</body>

</html>
